package org.example.config;

import lombok.extern.slf4j.Slf4j;
import org.example.handler.MyAccessDeniedHandler;
import org.example.handler.MyAuthenticationFailureHandler;
import org.example.handler.MyAuthenticationSuccessHandle;
import org.example.handler.MyLogoutSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

@Slf4j
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    MyAuthenticationSuccessHandle myAuthenticationSuccessHandle;
    @Resource
    MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    @Resource
    MyAccessDeniedHandler myAccessDeniedHandler;
    @Resource
    MyLogoutSuccessHandler myLogoutSuccessHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //任何访问均需要认证
        http.authorizeRequests().anyRequest().authenticated();
        //登录放行
        http.formLogin()
                .successHandler(myAuthenticationSuccessHandle)         //配置认证成功处理器
                .failureHandler(myAuthenticationFailureHandler)        //配置认证失败处理器
                .permitAll();


        http.logout().logoutSuccessHandler(myLogoutSuccessHandler);
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}